package com.sdy.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 工具类，用来捕获ApplicationContext对象，并对其进行设置
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 用来设置ApplicationContext的值的方法
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 根据名字获取
     * @param name
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name){
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 根据类型获取
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz){
        checkApplicationContext();
        return (T) applicationContext.getBean(clazz);
    }

    /**
     * 清除上下文对象
     * @return
     */
    public static void cleanApplicationContext(){
        applicationContext = null;
    }

    /**
     * 用来获取ApplicationContext对象的方法
     */
    public ApplicationContext getApplicationContext(){
        checkApplicationContext();
        return applicationContext;
    }

    /**
     * 检查applicationcontext属性是否为空
     */
    public static void checkApplicationContext(){
        if (applicationContext == null){
            throw new IllegalStateException("applicationContext对象未注入");

        }
    }
}
